package cn.org.itool.demo.vo;

import cn.org.itool.common.constent.CodeEnum;
import cn.org.itool.web.function.ConvertFunction;
import cn.org.itool.web.resp.Out;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 分页返回数据
 *
 * @author 祥霸
 * @version 1.0
 * @param <T>
 */
@Data
public class PageOut<T>{

    private int code;

    private String desc;

    private PageData<T> data;


    public static PageOut<String> success() {
        return PageOut.buildResponse(CodeEnum.SUCCESS.code(), "", null);
    }

    public static <T> PageOut<T> success(IPage<T> data) {
        return PageOut.buildResponse(CodeEnum.SUCCESS.code(), "", data);
    }

    public static <T, S> PageOut<T> success(IPage<S> data, ConvertFunction<T, S> convertFunction) {
        PageOut<T> out = new PageOut<>(CodeEnum.SUCCESS.code(), "");
        PageData<T> pageData = new PageData<>();
        pageData.setTotal(data.getTotal());
        List<T> dtoList = new ArrayList<>();
        for (S s : data.getRecords()) {
            dtoList.add(convertFunction.sToT(s));
        }
        pageData.setList(dtoList);
        out.setData(pageData);
        return out;
    }

    public static <T> PageOut<T> build(CodeEnum errorCode) {
        return new PageOut<>(errorCode.code(), errorCode.msg());
    }

    public static <T> Out<T> build(int code, String msg) {
        return new Out<>(code, msg);
    }

    public static <T> Out<T> build(CodeEnum errorCode, T data) {
        return new Out<>(errorCode.code(), errorCode.msg(), data);
    }

    public boolean isSuccess() {
        return CodeEnum.SUCCESS.code() == this.code;
    }

    public static <T> PageOut<T> buildResponse(int code, String msg, IPage<T> data) {
        return new PageOut<>(code, msg, data);
    }

    public PageOut(int code, String desc, IPage<T> page) {

        PageData<T> pageData = new PageData<>();

        if(Objects.nonNull(page)) {
            pageData.setTotal(page.getTotal());
            pageData.setList(page.getRecords());
        }


        this.code = code;
        this.desc = desc;
        this.data = pageData;
    }

    public PageOut(int code, String desc) {
        this.code = code;
        this.desc = desc;
    }
}
